package com.bcmusic.order.controller;

import com.bcmusic.music.feign.MusicFeign;
import com.bcmusic.order.config.TokenDecode;
import com.bcmusic.order.domain.orders.dto.CreateTransferDTO;
import com.bcmusic.order.domain.orders.vo.CreateOrdersVO;
import com.bcmusic.order.domain.orders.vo.CreateTransferVO;
import com.bcmusic.order.pojo.Orders;
import com.bcmusic.order.service.OrderCartService;
import com.bcmusic.order.service.OrdersService;
import com.github.pagehelper.PageInfo;
import entity.Result;
import entity.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/****
 * @Author:admin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/
@Api(value = "/orderCart", tags = "订单模块")
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderCartService orderCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private MusicFeign musicFeign;

    /***
     * Orders分页条件搜索实现
     * @param orders
     * @param page
     * @param size
     * @return
     */
    @ApiIgnore
    @PostMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@RequestBody(required = false) Orders orders, @PathVariable int page, @PathVariable int size) {
        //调用OrdersService实现分页条件查询Orders
        PageInfo<Orders> pageInfo = ordersService.findPage(orders, page, size);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * Orders分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size) {
        //调用OrdersService实现分页查询Orders
        PageInfo<Orders> pageInfo = ordersService.findPage(page, size);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param orders
     * @return
     */
    @ApiIgnore
    @PostMapping(value = "/search")
    public Result<List<Orders>> findList(@RequestBody(required = false) Orders orders) {
        //调用OrdersService实现条件查询Orders
        List<Orders> list = ordersService.findList(orders);
        return new Result<List<Orders>>(true, StatusCode.OK, "查询成功", list);
    }


    /***
     * 修改Orders数据
     * @param orders
     * @param id
     * @return
     */
    @ApiIgnore
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody Orders orders, @PathVariable Integer id) {
        //设置主键值
        orders.setOrderId(id);
        //调用OrdersService实现修改Orders
        ordersService.update(orders);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /***
     * 新增Orders数据
     * @param orders
     * @return
     */
    @ApiIgnore
    @PostMapping
    public Result add(@RequestBody Orders orders) {
        //调用OrdersService实现添加Orders
        ordersService.add(orders);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /***
     * 根据ID查询Orders数据
     * @param id
     * @return
     */
    @ApiIgnore
    @GetMapping("/{id}")
    public Result<Orders> findById(@PathVariable Integer id) {
        //调用OrdersService实现根据主键查询Orders

        Orders orders = ordersService.findById(id);
        return new Result<Orders>(true, StatusCode.OK, "查询成功", orders);
    }

    /***
     * 查询该用户全部订单
     * @return
     */
    @GetMapping("findAll")
    public Result<List<Orders>> findAll() {
//        Orders orders=new Orders();
//        String userNum = tokenDecode.getUserInfo().get("id");
//        orders.setAuthorizedNumber(userNum);
//        //调用OrdersService实现查询所有Orders
//        List<Orders> list = ordersService.findList(orders);
//        return new Result<List<Orders>>(true, StatusCode.OK,"查询成功",list) ;
        return null;
    }


    /**
     * 重点：创建订单，目前打算是：1.调用这个接口在redis获取购物车数据，然后创建一个总的订单，此时将redis对应的购物车数据存放到数据库中
     * 并删除redis对应数据，然后订单详情那一部分等待rabbitmq消息队列确认用户已支付，再从数据库中查出响应数据创建订单。
     * <p>
     * 未测试
     *
     * @param permissionIdList
     * @return
     */
    @ApiOperation(value = "创建订单,购物车结算许可商品时调用", notes = "传入musicNum列表,之后后台会自动删除对应的购物车")
    @PostMapping("createPermissionOrder")
    public Result<CreateOrdersVO> createPermissionOrder(@ApiParam(value = "购物车列表对应的permissionId列表 permissionIdList", name = "permissionIdList") @RequestParam String permissionIdList) {
        String userNum = tokenDecode.getUserInfo().get("id");
        //TODO 校验是否有未支付订单
        List<Integer> arrayList = new ArrayList<>();
        if (!permissionIdList.contains("-")) {
            arrayList.add(Integer.valueOf(permissionIdList));
        } else {
            String[] split = permissionIdList.split("-");
            for (String s : split) {
                arrayList.add(Integer.valueOf(s));
            }
        }

        CreateOrdersVO order = ordersService.createOrder(userNum, arrayList);
        if (order == null) {
            return new Result<>(true, StatusCode.ERROR, "创建订单失败，请返回购物车页面刷新重试");
        }
        return new Result<>(true, StatusCode.OK, "创建订单成功", order);
    }

    @ApiOperation(value = "提交订单", notes = "返回一个订单id，前端根据这个id调用微信支付的接口")
    @PostMapping("submitOrder")
    public Result<Map<String, String>> submitOrder(@ApiParam(value = "生成的预订单的id", name = "orderId") @RequestParam String orderId) {
        String userNum = tokenDecode.getUserInfo().get("id");
        Map<String, String> map = ordersService.submitOrders(userNum, orderId);
        if (map == null) {
            return new Result<>(true, StatusCode.ERROR, "订单已失效");
        } else {
            return new Result<>(true, StatusCode.OK, "提交订单成功", map);
        }
    }

    @ApiOperation(value = "转让模块生成订单，直接在购买页面跳转到这里，不需要经过购物车，类似于抢购", notes = "转让模块生成订单，直接在购买页面跳转到这里，不需要经过购物车，类似于抢购")
    @PostMapping("createTransferOrder")
    public Result<CreateTransferVO> createTransferOrder(CreateTransferDTO createTransferDTO) throws Exception {
        String userNum = tokenDecode.getUserInfo().get("id");
        CreateTransferVO transferOrder = ordersService.createTransferOrder(createTransferDTO, userNum);
        if (transferOrder == null) {
            return new Result<>(true, StatusCode.ERROR, "商品已售空，请下次再试");
        }
        return new Result<>(true, StatusCode.OK, "订单创建成功，请半小时内支付", transferOrder);
    }

}
